package tcpserver.client;

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * SL651协议增强测试客户端
 * 
 * 基于记忆中的SL651协议规范，包含更全面的测试用例
 */
public class SL651EnhancedTestClient {
    
    private static final String HOST = "localhost";
    private static final int PORT = 8281;
    
    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;
    
    /**
     * 连接到服务器
     */
    public boolean connect() {
        try {
            socket = new Socket(HOST, PORT);
             writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            
            
            System.out.println("=================================");
            System.out.println("   🚀 SL651增强测试客户端启动");
            System.out.println("   服务器地址: " + HOST + ":" + PORT);
            System.out.println("=================================");
            
            // 启动接收消息的线程
            startReceiveThread();
            
            return true;
            
        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 启动接收消息的线程
     */
    private void startReceiveThread() {
        Thread receiveThread = new Thread(() -> {
            try {
                String response;
                while ((response = reader.readLine()) != null) {
                    System.out.println("📨 [" + getCurrentTime() + "] 服务器响应: " + response);
                }
            } catch (IOException e) {
                if (!socket.isClosed()) {
                    System.err.println("接收消息失败: " + e.getMessage());
                }
            }
        });
        
        receiveThread.setDaemon(true);
        receiveThread.start();
    }
    
    /**
     * 发送消息
     */
    public void sendMessage(String message) {
        if (writer != null) {
            writer.println(message);
            System.out.println("📤 [" + getCurrentTime() + "] 发送: " + message);
        } else {
            System.err.println("连接未建立");
        }
    }
    
    /**
     * 获取当前时间
     */
    private String getCurrentTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }
    
    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            if (writer != null) {
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (socket != null) {
                socket.close();
            }
            System.out.println("🔌 连接已断开");
        } catch (IOException e) {
            System.err.println("断开连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行全面的SL651协议测试
     */
    public void runComprehensiveTest() {
        System.out.println("\\n🧪 开始执行SL651协议全面测试...\\n");
        
        try {
            // 等待连接稳定
            Thread.sleep(1000);
            
            // 第一阶段：基础HEX报文测试
            testBasicHexMessages();
            
            // 第二阶段：扩展HEX报文测试
            testExtendedHexMessages();
            
            // 第三阶段：ASCII报文测试
            testAsciiMessages();
            
            // 第四阶段：功能码测试
            testFunctionCodes();
            
            // 第五阶段：数据元素测试
            testDataElements();
            
            // 第六阶段：错误处理测试
            testErrorHandling();
            
            // 第七阶段：性能测试
            testPerformance();
            
            System.out.println("\\n✅ SL651协议全面测试完成！\\n");
            
        } catch (InterruptedException e) {
            System.err.println("测试过程被中断: " + e.getMessage());
        }
    }
    
    /**
     * 基础HEX报文测试
     */
    private void testBasicHexMessages() throws InterruptedException {
        System.out.println("🔹 第一阶段：基础HEX报文测试");
        
        // 测试1：标准遥测数据上报
        sendMessage("68 10 00 10 00 68 81 38 00 00 00 00 00 1F 06 C0 16");
        Thread.sleep(500);
        
        // 测试2：心跳包
        sendMessage("68 0A 00 0A 00 68 82 01 00 00 00 16");
        Thread.sleep(500);
        
        // 测试3：时间同步请求
        sendMessage("68 0C 00 0C 00 68 83 01 00 20 25 08 29 12 16");
        Thread.sleep(500);
        
        // 测试4：实时数据查询
        sendMessage("68 0E 00 0E 00 68 84 30 00 01 02 03 04 05 16");
        Thread.sleep(500);
        
        System.out.println("✓ 基础HEX报文测试完成\\n");
    }
    
    /**
     * 扩展HEX报文测试
     */
    private void testExtendedHexMessages() throws InterruptedException {
        System.out.println("🔹 第二阶段：扩展HEX报文测试");
        
        // 测试5：长报文（水情数据）
        sendMessage("68 20 00 20 00 68 85 38 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 16");
        Thread.sleep(500);
        
        // 测试6：无空格HEX格式
        sendMessage("680A000A00688201000000016");
        Thread.sleep(500);
        
        // 测试7：混合大小写HEX
        sendMessage("68 0a 00 0A 00 68 82 01 00 00 00 16");
        Thread.sleep(500);
        
        System.out.println("✓ 扩展HEX报文测试完成\\n");
    }
    
    /**
     * ASCII报文测试
     */
    private void testAsciiMessages() throws InterruptedException {
        System.out.println("🔹 第三阶段：ASCII报文测试");
        
        // 测试8：标准ASCII报文
        sendMessage("$12345678901234567890123456789012345678#");
        Thread.sleep(500);
        
        // 测试9：时间同步ASCII
        sendMessage("$SYNC20250829142200#");
        Thread.sleep(500);
        
        // 测试10：水位数据
        sendMessage("$WL125.67M20250829142200#");
        Thread.sleep(500);
        
        // 测试11：雨量数据
        sendMessage("$RF012.5MM20250829142200#");
        Thread.sleep(500);
        
        // 测试12：温度数据
        sendMessage("$TEMP23.5C20250829142200#");
        Thread.sleep(500);
        
        System.out.println("✓ ASCII报文测试完成\\n");
    }
    
    /**
     * 功能码测试
     */
    private void testFunctionCodes() throws InterruptedException {
        System.out.println("🔹 第四阶段：功能码测试");
        
        // 功能码测试 - 根据SL651规范
        String[] functionCodes = {"2F", "30", "31", "32", "33", "34", "35", "36", "37", "38"};
        
        for (int i = 0; i < functionCodes.length; i++) {
            String testMessage = "68 0C 00 0C 00 68 81 " + functionCodes[i] + " 00 00 00 00 16";
            sendMessage("功能码" + functionCodes[i] + "测试: " + testMessage);
            Thread.sleep(300);
        }
        
        System.out.println("✓ 功能码测试完成\\n");
    }
    
    /**
     * 数据元素测试
     */
    private void testDataElements() throws InterruptedException {
        System.out.println("🔹 第五阶段：数据元素测试");
        
        // 数据元素测试 - 根据SL651规范
        String[] dataElements = {
            "$ST001#", "$TT20250829142200#", "$PJ1234#", "$Z125.67#", 
            "$VT12.5#", "$H67.8#", "$T23.5#", "$TW18.2#", "$PH7.2#",
            "$WD180#", "$WS5.2#", "$EV12.3#", "$PA1013.2#", "$VI12.5#"
        };
        
        for (String element : dataElements) {
            sendMessage("数据元素测试: " + element);
            Thread.sleep(300);
        }
        
        System.out.println("✓ 数据元素测试完成\\n");
    }
    
    /**
     * 错误处理测试
     */
    private void testErrorHandling() throws InterruptedException {
        System.out.println("🔹 第六阶段：错误处理测试");
        
        // 测试无效报文
        sendMessage("INVALID_HEX_DATA");
        Thread.sleep(300);
        
        // 测试不完整报文
        sendMessage("68 10 00");
        Thread.sleep(300);
        
        // 测试无效ASCII格式
        sendMessage("$INCOMPLETE");
        Thread.sleep(300);
        
        // 测试空消息
        sendMessage("");
        Thread.sleep(300);
        
        System.out.println("✓ 错误处理测试完成\\n");
    }
    
    /**
     * 性能测试
     */
    private void testPerformance() throws InterruptedException {
        System.out.println("🔹 第七阶段：性能测试");
        
        long startTime = System.currentTimeMillis();
        
        // 批量发送100条报文
        for (int i = 1; i <= 100; i++) {
            String message = "68 10 00 10 00 68 81 38 00 00 00 00 " + String.format("%02X", i) + " 1F 06 C0 16";
            sendMessage("性能测试" + i + ": " + message);
            
            if (i % 20 == 0) {
                Thread.sleep(100); // 每20条消息暂停一下
            }
        }
        
        long endTime = System.currentTimeMillis();
        System.out.println("⏱️  性能测试完成，耗时: " + (endTime - startTime) + "ms");
        System.out.println("✓ 性能测试完成\\n");
    }
    
    /**
     * 主程序入口
     */
    public static void main(String[] args) {
        SL651EnhancedTestClient client = new SL651EnhancedTestClient();
        
        // 连接服务器
        if (!client.connect()) {
            System.err.println("无法连接到服务器，请确保服务器正在运行");
            return;
        }
        
        try {
            // 执行全面测试
            client.runComprehensiveTest();
            
            // 等待一段时间确保所有响应都收到
            Thread.sleep(3000);
            
            // 发送退出命令
            client.sendMessage("QUIT");
            Thread.sleep(1000);
            
        } catch (InterruptedException e) {
            System.err.println("程序被中断: " + e.getMessage());
        } finally {
            client.disconnect();
            System.out.println("\\n🎯 SL651增强测试客户端测试完成！");
            System.out.println("📊 测试覆盖了HEX/ASCII编码、功能码、数据元素、错误处理和性能测试");
        }
    }
}